package com.example.controller;

import com.example.aspect.annotation.AllowAnon;
import com.example.response.AjaxJson;
import com.example.utils.ImageChecker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "文件相关接口")
@RequestMapping("/file")
public class UploadController {
    @Value("${file.uploader.path}")
    private String uploadPath;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public AjaxJson upload(@RequestParam MultipartFile file) throws IOException {
        //得到文件的原始文件名
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        //为了防止图片的名字相同导致的覆盖,需要设置唯一性名字,做以下操作
        //得到文件名后缀   最后一个点的位置截取到最后即a.jpg得到.jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //后缀得到后,得到唯一文件名   UUID.randomUUID()获得一个字符串类型的唯一标识符
        fileName = UUID.randomUUID() + suffix;
        //保存到磁盘中
        //准备文件夹路径
        String dirPath = uploadPath;
        String type = suffix.split("[.]")[1].toLowerCase();

        boolean imageFile = ImageChecker.isImageFile(file);
        if (imageFile) {
            type = "image";
        }

        String datePath = "/" + type + "/";

        //创建文件夹
        //d:/files/yyyy/MM/dd/
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()) {//这个路径的文件夹如果不存在,则创建
            dirFile.mkdirs();
        }

        file.transferTo(new File(dirPath + datePath + fileName));

        String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path(datePath + fileName)
                .toUriString();
        return AjaxJson.ok(fileUrl);


    }

}
